package net.qiqbframework.common.resolving;

import java.lang.annotation.Annotation;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ResolvedAttributesUtil {

    /**
     * 从注解属性中过滤筛选出指定注解的属性
     *
     * @param resolvedAttributes 所有注解
     * @param annotationType     指定注解
     * @return 指定注解的属性。如果没有值得注解类型，则返回空
     */
    public static Optional<Map<String, Object>> filterAnnotationAttributes(ResolvedAttributes resolvedAttributes, Class<? extends Annotation> annotationType) {
        if (resolvedAttributes == null || annotationType == null) {
            return Optional.empty();
        }
        String annotationTypeName = annotationType.getSimpleName();
        final Map<String, Object> all = resolvedAttributes.getAll();
        final Map<String, Object> filterAttributes = all.entrySet().stream()
                .filter(entry -> entry.getKey().startsWith(annotationTypeName + "."))
                .collect(Collectors.toMap(entry -> entry.getKey().substring(entry.getKey().indexOf(".") + 1), Map.Entry::getValue));
        if (filterAttributes.isEmpty()) {
            return Optional.empty();
        }
        return Optional.of(filterAttributes);
    }
}
